package com.hbnu.tangyalu.jdbc;

import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;

public class JdbcDemo04 {
    public static void main(String[] args) {
        Map<String,String> userInfo =initUI();
        boolean flag=verifiedUserInfo(userInfo);
        System.out.println(flag?"登录成功":"登录失败");
    }

    private static boolean verifiedUserInfo(Map<String, String> userInfo) {
        boolean flag=false;//登录成功或失败的标记
//        从userInfo内获取账号密码
        String username=userInfo.get("username");
        String password=userInfo.get("password");
        Connection connection=null;
        Statement statement=null;
        ResultSet resultSet=null;
        PreparedStatement preparedStatement=null;
        try {
            String url="jdbc:mysql://localhost:3306/class2311?serverTimezone=GMT&useSSL=false&characterEncoding=utf-8";
            String name="root";
            String pwd="123456";
            connection= DriverManager.getConnection(url,name,pwd);
//            statement=connection.createStatement();
//            String sql="select * from tb_user where username ='"+username+"'and password='"+password+"'";
//            resultSet=statement.executeQuery(sql);
            String sql="select * from tb_user where username=? and password=?";
            preparedStatement=connection.prepareStatement(sql);
            preparedStatement.setString(1,username);
            preparedStatement.setString(2,password);
            resultSet=preparedStatement.executeQuery();
            while (resultSet.next()){
                flag=true;
                break;
            }
        }
        catch (Exception e){
            throw new RuntimeException(e);
        }
        finally {
//            关闭资源从小到大，一个一个的关闭
            try {
                if (resultSet!=null){
                    resultSet.close();
                }
            }
            catch (Exception e){
                e.printStackTrace();
            }

            try {
                if (preparedStatement!=null){
                    preparedStatement.close();
                }
            }
            catch (SQLException e){
                e.printStackTrace();
            }

            try {
                if (connection!=null){
                    connection.close();
                }
            }catch (SQLException e){
                e.printStackTrace();
            }
        }
        return false;
    }

    private static Map<String, String> initUI() {
        Map<String,String> userInfo=new HashMap<>();
        Scanner scanner=new Scanner(System.in);
        System.out.println("请输入你的账号：");
        String username= scanner.nextLine();
        System.out.println("请输入你的密码：");
        String password= scanner.nextLine();

        return null;
    }
}
